package com.wzh.common.feign.exception;

import com.wzh.common.general.exception.CustomerException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * Feign远程调用异常处理器，统一处理微服务间调用时的异常情况
 * </p>
 *
 * @author 山归岿
 * @create 2025-06-15-19:42
 */
@Slf4j
@Component
public class FeignExceptionHandler implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        log.error("Feign调用异常，方法: {}, 状态码: {}, 原因: {}",
                methodKey, response.status(), response.reason());

        return switch (response.status()) {
            case 400 -> new CustomerException("请求参数错误");
            case 401 -> new CustomerException("未授权访问");
            case 403 -> new CustomerException("禁止访问");
            case 404 -> new CustomerException("请求的资源不存在");
            case 500 -> new CustomerException("服务器内部错误");
            case 503 -> new CustomerException("服务不可用");
            default -> new CustomerException("远程调用失败，状态码: " + response.status());
        };
    }
}